import { ContactModel } from '~/model/ContactModel'
import { JobRecordModel } from '~/model/JobRecordModel'

export abstract class JobRecordSerializer {
  static serialize(model: JobRecordModel): SentData {
    if (!model.worker) {
      throw new Error(`JobRecordSerializer.serialize: model.worker => ${model.worker}`)
    }
    return {
      workerId: model.worker.id,
      date: model.date.valueOf(),
      content: JSON.stringify({
        action: model.action as number,
        params: model.actionParams,
      }),
    }
  }

  static async deserialize(data: ReceivedData): Promise<JobRecordModel> {
    const model = new JobRecordModel()
    const contentObj = JSON.parse(data.content)

    model.id = data.id
    model.worker = await ContactModel.fromId(data.workerId)
    model.date = new Date(data.date)
    model.action = contentObj.action
    model.actionParams = contentObj.params
    return model
  }
}

interface SentData {
  workerId: number
  date: number
  content: string
}

interface ReceivedData {
  id: number
  workerId: number
  date: number
  content: string
}
